import React, { useContext, useEffect, useReducer } from 'react';
import axios from 'axios';

const GlobalContext = React.createContext();

function Film(props) {
      let {name,detail} = props;
      const {dispatch} = useContext(GlobalContext);
          //消费者模式
        return(
            <div>
            <span style={{cursor:'pointer'}} onClick={()=>{
            dispatch({
                type:'change-detail',
                value:detail
            })
            }}>{name}</span>
            </div>
        )
  }
  const reducer = (oldstate, action)=>{   //reducer进行处理，action中存储dispatch的东西
    let newstate = {...oldstate};
    switch(action.type){
        case 'change-filmlist':
            newstate.list = action.value;
            return newstate;
        case 'change-detail':
            newstate.detail = action.value;
            return newstate;
        default:
            return oldstate;
    }
  }

  const initvalue ={   //reducer要设置state的初始值
      list:[],
      detail:""
  }

export default function App() {
      const [state, dispatch] = useReducer(reducer, initvalue);
      useEffect(()=>{
        axios({
            url:'https://m.maizuo.com/gateway?cityId=440300&pageNum=1&pageSize=10&type=1&k=3889594',
            headers:{
              'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.0","e":"165294070798642513887233"}',
              'X-Host': 'mall.film-ticket.film.list'
            }
        }).then(res =>{
            dispatch({                       //dispatch负责对数据进行改变
                type:'change-filmlist',
                value: res.data.data.films
            })
            console.log(res.data.data.films);
        })
      },[])
      return (
        <GlobalContext.Provider value={   //生产者模式
          {
            state,
            dispatch
          }
        }>
          <div>
            {
              state.list.map((item)=>
                <Film key={item.filmId} name={item.name} detail={item.synopsis}></Film>
              )
            }
            <Film2 detail={state.detail}></Film2>
         </div>
        </GlobalContext.Provider>
      )
  }



function Film2(){
    const {state} = useContext(GlobalContext);
        return (
            <div style={{
                background:'yellow',
                position:'fixed',
                right:0,
                width:'300px',
                height:'300px'
                }}>{state.detail}
            </div>
        )
}

